const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 8080;
app.use(express.static(__dirname + '../html/Login.html'))
// 允许所有域名的跨域请求
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});



// 文件上传路由
app.post('/resumeStatus/upload/:usersId', (req, res) => {
  const usersId = req.params.usersId;
  const uploadDir = 'uploads';
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
  }

  const contentDisposition = req.headers['content-disposition'];
  if (!contentDisposition) {
    return res.status(400).json({ code: 0, msg: '未找到文件信息' });
  }

  const filename = contentDisposition.split('filename=').pop().split(';').shift();
  if (!filename) {
    return res.status(400).json({ code: 0, msg: '未找到文件名' });
  }

  const filePath = path.join(uploadDir, `${Date.now()}-${filename}`);
  const fileStream = fs.createWriteStream(filePath);

  req.pipe(fileStream);

  fileStream.on('finish', () => {
    fileStream.close((err) => {
      if (err) {
        return res.status(500).json({ code: 0, msg: '服务器错误' });
      }
      res.json({ code: 1, msg: '上传成功', data: `/uploads/${path.basename(filePath)}` });
    });
  });

  fileStream.on('error', (err) => {
    res.status(500).json({ code: 0, msg: '服务器错误' });
  });
});

app.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(__dirname, 'uploads', filename);
  if (fs.existsSync(filePath)) {
    res.download(filePath);
  } else {
    res.status(404).send('文件不存在');
  }
});

app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
});

app.get('/resumeStatus/view/:userId', (req, res) => {
  const userId = req.params.userId;
  const resume = resumes.find(r => r.id === parseInt(userId));
  if (resume) {
    if (resume.fileUrl) {
      res.json({ code: 1, data: { ...resume, userType: 'file' } });
    } else {
      res.json({ code: 1, data: { ...resume, userType: 'form' } });
    }
  } else {
    res.json({ code: 0, msg: '简历不存在' });
  }
});